const { SerialPort } = require("serialport");
const { ReadlineParser } = require("@serialport/parser-readline");
const { closeCabinetByNum } = require('../repositories/cabinetRepositories')
const WebSocket = require('ws'); // 引入ws模块

class USARTService {
  constructor(portName, baudRate) {
    this.portName = portName;
    this.baudRate = baudRate;
    this.port = null;
    this.parser = null;
    this.isInitialized = false; // 添加初始化状态标记
  }

  async initialize() {
    try {
      // 创建串口实例，但不自动打开
      this.port = new SerialPort({
        path: this.portName,
        baudRate: this.baudRate,
        dataBits: 8,
        stopBits: 1,
        parity: "none",
        autoOpen: false, // 禁用自动打开
      });

      // 手动打开串口
      await this.port.open();

      console.log("串口已打开");

      // 创建解析器
      this.parser = this.port.pipe(new ReadlineParser());

      this.port.on("close", () => {
        console.log("串口已关闭");
      });

      this.port.on("error", (err) => {
        console.error("串口错误:", err.message);
      });

      // 监听接收到的数据
      this.parser.on("data", (data) => {
        console.log(`从STM32收到的数据: ${data}`);
        if (data !== null && data.slice(0, 7) === 'closed@')
          closeCabinetByNum(data.slice(7, 8))
        // 将接收到的数据发送给所有WebSocket客户端----------------------------------------------------
        if (global.wss) {
          global.wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
              client.send(JSON.stringify({ data }))
            }
          });
        }
      });

      this.isInitialized = true; // 初始化完成
      return { success: true, message: "串口初始化成功" };
    } catch (err) {
      console.error("打开串口失败:", err.message);
      this.isInitialized = false; // 初始化失败
      return { success: false, message: `串口初始化失败: ${err.message}` }
    }
  }

  sendData(data) {
    if (!this.isInitialized || !this.port) {
      console.error("串口尚未初始化或未打开")
      return;
    }

    this.port.write(data + "\r\n", (err) => {
      if (err) {
        console.error("发送数据错误:", err.message);
      } else {
        console.log(`发送到STM32的数据: ${data}`);
      }
    });
  }

  close() {
    if (this.port) {
      try {
        this.port.close();
        return true
      } catch (e) {
        throw e
      }
    }
  }
}

module.exports = USARTService;
